Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
graphql-tag
Advanced tools
The graphql-tag npm package is primarily used for parsing GraphQL queries and fragments into a standard GraphQL AST (Abstract Syntax Tree). It is commonly used in JavaScript or TypeScript projects that interact with a GraphQL server. The package provides a simple and efficient way to embed GraphQL queries within the code.
Parsing GraphQL queries
This feature allows developers to write GraphQL queries inside JavaScript or TypeScript files using template literals. The gql function parses the query string into a GraphQL AST, which can then be used with GraphQL clients like Apollo Client.
import gql from 'graphql-tag';
const MY_QUERY = gql`
query GetUserInfo($userId: ID!) {
user(id: $userId) {
id
name
email
}
}
`;
Parsing GraphQL fragments
This feature allows the definition of GraphQL fragments that can be reused across multiple queries or mutations. The gql function is used to parse the fragment, and it can be embedded within queries or mutations to avoid repetition of field definitions.
import gql from 'graphql-tag';
const USER_FRAGMENT = gql`
fragment UserFragment on User {
id
name
email
}
`;
const MY_QUERY = gql`
query GetUserInfo($userId: ID!) {
user(id: $userId) {
...UserFragment
}
}
${USER_FRAGMENT}
`;
Support for multiple operations in a single document
graphql-tag supports defining multiple operations, such as queries and mutations, within a single gql template literal. This can be useful for organizing related operations together in one place.
import gql from 'graphql-tag';
const MULTIPLE_OPERATIONS = gql`
query GetUserInfo($userId: ID!) {
user(id: $userId) {
id
name
}
}
mutation UpdateUserName($userId: ID!, $newName: String!) {
updateUser(id: $userId, name: $newName) {
id
name
}
}
`;
The 'graphql' package is the core JavaScript implementation of GraphQL itself. It includes functionality for parsing queries, but it's more general-purpose and lower-level compared to graphql-tag. It does not provide the same template literal syntax for embedding queries.
Apollo Boost is a package that includes graphql-tag as one of its dependencies. It provides a zero-config way to start using Apollo Client. It's more of a complete solution for managing GraphQL state in applications, whereas graphql-tag is focused solely on parsing queries.
graphql.macro provides similar functionality to graphql-tag but is designed to work with Create React App without ejecting. It allows you to load .graphql and .gql files at compile time, which graphql-tag does not do by default.
Helpful utilities for parsing GraphQL queries. Includes:
gql
A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST./loader
A webpack loader to preprocess queriesgraphql-tag
uses the reference graphql
library under the hood as a peer dependency, so in addition to installing this module, you'll also have to install graphql
.
The gql
template literal tag can be used to concisely write a GraphQL query that is parsed into a standard GraphQL AST. It is the recommended method for passing queries to Apollo Client. While it is primarily built for Apollo Client, it generates a generic GraphQL AST which can be used by any GraphQL client.
import gql from 'graphql-tag';
const query = gql`
{
user(id: 5) {
firstName
lastName
}
}
`
The above query now contains the following syntax tree.
{
"kind": "Document",
"definitions": [
{
"kind": "OperationDefinition",
"operation": "query",
"name": null,
"variableDefinitions": null,
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{
"kind": "Field",
"alias": null,
"name": {
"kind": "Name",
"value": "user",
...
}
}
]
}
}
]
}
The gql
tag can also be used to define reusable fragments, which can easily be added to queries or other fragments.
import gql from 'graphql-tag';
const userFragment = gql`
fragment User_user on User {
firstName
lastName
}
`
The above userFragment
document can be embedded in another document using a template literal placeholder.
const query = gql`
{
user(id: 5) {
...User_user
}
}
${userFragment}
`
Note: While it may seem redundant to have to both embed the userFragment
variable in the template literal AND spread the ...User_user
fragment in the graphQL selection set, this requirement makes static analysis by tools such as eslint-plugin-graphql
possible.
GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like eslint-plugin-graphql. However, strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff.
That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql
tag.
This package only has one feature - it caches previous parse results in a simple dictionary. This means that if you call the tag on the same query multiple times, it doesn't waste time parsing it again. It also means you can use ===
to compare queries to check if they are identical.
To add support for importing .graphql
/.gql
files, see Webpack loading and preprocessing below.
Given a file MyQuery.graphql
query MyQuery {
...
}
If you have configured the webpack graphql-tag/loader, you can import modules containing graphQL queries. The imported value will be the pre-built AST.
import MyQuery from 'query.graphql'
You can also import query and fragment documents by name.
query MyQuery1 {
...
}
query MyQuery2 {
...
}
And in your JavaScript:
import { MyQuery1, MyQuery2 } from 'query.graphql'
Preprocessing GraphQL queries and fragments into ASTs at build time can greatly improve load times.
GraphQL queries can be compiled at build time using babel-plugin-graphql-tag. Pre-compiling queries decreases script initialization time and reduces bundle sizes by potentially removing the need for graphql-tag
at runtime.
Try this custom transformer to pre-compile your GraphQL queries in TypeScript: ts-transform-graphql-tag.
Preprocessing queries via the webpack loader is not always possible. babel-plugin-import-graphql supports importing graphql files directly into your JavaScript by preprocessing GraphQL queries into ASTs at compile-time.
E.g.:
import myImportedQuery from './productsQuery.graphql'
class ProductsPage extends React.Component {
...
}
Using the included graphql-tag/loader
it is possible to maintain query logic that is separate from the rest of your application logic. With the loader configured, imported graphQL files will be converted to AST during the webpack build process.
Example webpack configuration
{
...
loaders: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader'
}
],
...
}
Preprocessing GraphQL imports is supported in create-react-app >= v2 using evenchange4/graphql.macro.
For create-react-app < v2, you'll either need to eject or use react-app-rewire-inline-import-graphql-ast.
Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.
With the webpack loader, you can import fragments by name:
In a file called query.gql
:
fragment MyFragment1 on MyType1 {
...
}
fragment MyFragment2 on MyType2 {
...
}
And in your JavaScript:
import { MyFragment1, MyFragment2 } from 'query.gql'
Note: If your fragment references other fragments, the resulting document will
have multiple fragments in it. In this case you must still specify the fragment name when using the fragment. For example, with @apollo/client
you would specify the fragmentName
option when using the fragment for cache operations.
This package will emit a warning if you have multiple fragments of the same name. You can disable this with:
import { disableFragmentWarnings } from 'graphql-tag';
disableFragmentWarnings()
This package exports an experimentalFragmentVariables
flag that allows you to use experimental support for parameterized fragments.
You can enable / disable this with:
import { enableExperimentalFragmentVariables, disableExperimentalFragmentVariables } from 'graphql-tag';
Enabling this feature allows you declare documents of the form
fragment SomeFragment ($arg: String!) on SomeType {
someField
}
You can easily generate and explore a GraphQL AST on astexplorer.net.
FAQs
A JavaScript template literal tag that parses GraphQL queries
The npm package graphql-tag receives a total of 5,331,224 weekly downloads. As such, graphql-tag popularity was classified as popular.
We found that graphql-tag demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.